package com.redrose.videodemo.runnabletask;

import android.content.Context;
import android.media.AudioTrack;

import com.redrose.videodemo.utils.PathUtil;
import com.redrose.videodemo.utils.ToastUtil;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import static com.redrose.videodemo.utils.AudioRecordUtil.*;

/**
 * Desc:
 *
 * @Author: RedRose
 * Date: 2019/4/15 0015
 * Email: yinsxi@163.com
 */
public class PlayPCMRunnable implements Runnable {
    private AudioTrack audioTrack;
    private Context mContext;

    public PlayPCMRunnable(Context mContext) {
        this.mContext = mContext;
    }

    @Override
    public void run() {
        playPcm();
    }

    public void playPcm() {
        DataInputStream dis = null;
        File file = new File(PathUtil.getAppAudioPath(), "audio.pcm");
        if(!file.exists()){
            ToastUtil.show(mContext.getApplicationContext(),"音频文件不存在");
            return;
        }
        try {
            dis = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
            int bufferSize = AudioTrack.getMinBufferSize(AUDIO_SAMPLE_RATE, CHANNEL_CONFIG, AUDIO_FORMAT);
            audioTrack = new AudioTrack(AUDIORE_SOURCE, AUDIO_SAMPLE_RATE, CHANNEL_CONFIG, AUDIO_FORMAT, bufferSize, AudioTrack.MODE_STREAM);
            byte[] datas = new byte[bufferSize];
            audioTrack.play();
            while (true) {
                int i = 0;
                try {
                    while (dis.available() > 0 && i < datas.length) {
                        datas[i] = dis.readByte();
                        i++;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                audioTrack.write(datas, 0, datas.length);
                //表示读取完了
                if (i != bufferSize) {
                    audioTrack.stop();
                    audioTrack.release();
                    break;
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}
